<template>
  <div class="app-container">
    <el-container style="border: 1px solid #eee">
      <el-header style="height:auto;">
        <el-select v-model="project_id" v-loading="projectsLoading" placeholder="选择项目" filterable clearable>
          <el-option
            v-for="(item,index) in projects"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        只看自己:
        <el-switch
          v-model="myself"
          style="width: 100px;"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
        <el-select v-model="uploaded" size="mini" placeholder="状态" clearable>
          <el-option label="所有" value="all" />
          <el-option label="未上传" value="unuploaded" />
          <el-option label="已上传" value="uploaded" />
        </el-select>
        <el-select v-model="modify_finsihed" size="mini" placeholder="修改完成" clearable>
          <el-option label="所有" value="" />
          <el-option label="修改完成" value="true" />
          <el-option label="未修改" value="false" />
        </el-select>
        <el-input
          v-model="kwInput"
          placeholder="输入URL或者产品名称进行搜索"
          style="width: 40%"
          clearable
          class=""
          @keyup.native.enter="handleSearch"
        >
          <el-select
            slot="prepend"
            v-model="select_web"
            style="width: 200px;"
            filterable
            clearable
            placeholder="选择来源"
            @change="handleSearch"
          >
            <el-option label="所有" value="-1" />
            <el-option
              v-for="(item,index) in dataWebs"
              :key="index"
              :label="item.domain"
              :value="item.id"
            />
          </el-select>

          <el-button slot="append" style="width: 180px" type="success" icon="el-icon-search" @click="handleSearch">搜索
          </el-button>
        </el-input>
        <el-button type="success" @click="handleShowDialog">增加</el-button>
      </el-header>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          :default-sort="{prop: 'create_at', order: 'descending'}"
          style="width: 100%"
          @sort-change="handleSort"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            fixed
            prop="image"
            width="120"
            label="产品"
          >
            <template slot-scope="scope">
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
              />
            </template>
          </el-table-column>
          <el-table-column
            fixed
            sortable="custom"
            prop="url"
            label="信息"
          >
            <template slot-scope="scope">
              <small style="display: block">售价:{{ scope.row.price }} 运费:{{ scope.row.shipping_fee }}
                ship_from:{{ scope.row.ship_from }}</small>
              <small style="display: block">{{ scope.row.name }} <el-button type="text" @click="handleShowPCP(scope.row)">竞品</el-button></small>
              <a :href="scope.row.url" target="_blank">{{ scope.row.url }}</a>
              <small style="display: block">TAG: {{ scope.row.tag }} <span style="float: right">by {{ scope.row.creator }} {{ scope.row.create_at }}</span></small>

            </template>
          </el-table-column>
          <el-table-column
            fixed
            sortable="custom"
            prop="uploads"
            label="已上传网站"
          >
            <template slot-scope="scope">
              <el-tag v-if="!scope.row.change_price" type="danger">价格已修改:{{ scope.row.modify_price }}</el-tag>
              <ul>
                <li v-for="(item,index) in scope.row.uploads" :key="index">网站:{{ item.domain }}
                  task_id:{{ item.task_id }}
                  <a
                    v-if="item.is_finished"
                    :href="item.target_url"
                    target="_blank"
                  >id_product:{{ item.ps_product }}</a>
                  <!--                  <el-button size="mini" type="text" @click="handleGetRemoteProduct(item)">编辑产品</el-button>-->
                  <el-tag v-else>还没上传</el-tag>
                  <el-button type="text" icon="el-icon-edit" @click="handleShowEditWebsite(item.domain)" />
                  <el-button type="text" @click="handleShowAddReview(item)">添加review</el-button>
                </li>
              </ul>
            </template>
          </el-table-column>
          <el-table-column
            fixed
            prop="product_id"
            label="本地ID"
            width="100"
          />
          <el-table-column
            fixed="right"
            width="350"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              <el-button
                v-if="scope.row.product_id !== ''"
                size="mini"
                type="warning"
                @click="handleModifyProduct(scope.row)"
              >编辑本地产品
              </el-button>
              <el-button size="mini" type="success" @click="uploadShown(scope.row)">上传</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button v-if="select_rows.length" type="success" size="mini" style="float: right;margin-top: 5px;" @click="uploadMultipleSite">批量上传</el-button>
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>
    <el-dialog
      append-to-body
      title="添加新的产品URL"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="160px">
        <el-form-item label="网址">
          <el-input
            v-model="temp.urls"
            type="textarea"
            :autosize="{ minRows: 8}"
            placeholder="输入URL,每行一个"
            @change="handleFixUrl"
          />
        </el-form-item>
        <el-form-item label="Tag">
          <el-input v-model="temp.tag" />
        </el-form-item>
        <el-form-item label="ship_from">
          <el-input v-model="temp.ship_from" placeholder="发货地:US/CN" />
        </el-form-item>
        <el-form-item label="来源网站">
          <el-select v-model="temp.web_id" tyle="width: 100%" filterable clearable placeholder="来源网站">
            <el-option v-for="item in this.dataWebs" :key="item.id" :label="item.domain" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="modifyloading" @click="handleAddNew">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      append-to-body
      :title="'上传' + uploaddata.url"
      :visible.sync="uploadVisible"
      :close-on-click-modal="false"
    >
      <el-row>
        {{ uploaddata.products.length }}个产品:<span v-for="(item,index) in uploaddata.products" :key="index">{{ item }}|</span>
        <div style="float: right;display: block">
          <span>添加网站:</span>
          <el-select
            v-model="add_new_website_id"
            filterable
            clearable
            remote
            value-key="label"
            reserve-keyword
            placeholder="输入域名搜索网站"
            :remote-method="remoteSearchWebsite"
            :loading="remoteSearchWebsite_loading"
          >
            <el-option
              v-for="(item,index) in website_options"
              :key="index"
              :label="item.domain"
              :value="item.id"
            />
          </el-select>
          <el-button @click="handleAddNewWebsite">添加</el-button>
        </div>
      </el-row>
      <el-row>
        <el-col>
          <el-table
            :data="uploaddata.selected_websites"
            border
            style="width: 100%;border:2px solid black;color:black"
          >
            <el-table-column
              fixed
              sortable
              prop="website_id"
              label="website_id"
            />
            <el-table-column
              fixed
              sortable
              prop="domain"
              label="domain"
            />
            <el-table-column
              fixed
              sortable
              prop="id_of_default_category"
              label="默认目录"
            />
            <el-table-column
              fixed
              sortable
              prop="id_of_associated_categories"
              label="关联目录"
            >
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.id_of_associated_categories" :key="index" type="danger">
                  {{ item }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              fixed
              label="操作"
              width="300"
            >
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.id_of_default_category !== ''"
                  size="mini"
                  title="配置目录"
                  type="default"
                  @click="handleSetCategory(scope.row)"
                >配置目录
                </el-button>
                <el-button v-else size="mini" title="配置目录" type="danger" @click="handleSetCategory(scope.row)">配置目录
                </el-button>
                <el-button type="text" size="small" @click="handleRemoveTargetWeb(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>

      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadVisible = false">取 消</el-button>
        <el-button type="primary" :loading="modifyloading" @click="handleUpload">确 定</el-button>
      </span>
    </el-dialog>
    <prestaproduct
      :domain="operate_domain"
      :product_id="operate_product_id"
      :local_id="operate_local_id"
      :pst-visible="remoteModifydialogVisible"
      @closePstDialog="handlePstClose"
    />
    <merchant :merchant-visible="merchantVisible" @closeMerchantDialog="merchantVisible=false" />
    <choosecategory
      :website_id="current_category.target_web_id"
      :choosedialog-visible="direct_upload_dialogVisible"
      :default_catalog="current_category.id_of_default_category"
      :default-checked-keys="current_category.id_of_associated_categories"
      @SetChoose="handleSetDirectUploadCategories"
      @closeDialog="direct_upload_dialogVisible=false"
    />
    <website_editor
      :domain="operate_domain"
      :is-visible="isWebsiteEditorVisible"
      @close="isWebsiteEditorVisible=false"
    />
    <platformcompetitiveproduct
      :is-visible="isVisible_platformcompetitiveproduct"
      :keyword="keyword_platformcompetitiveproduct"
      :image="image_platformcompetitiveproduct"
      :price="price_platformcompetitiveproduct"
      @closeMyDialog="isVisible_platformcompetitiveproduct=false"
    />
    <websitereviews :is-visible="reviewVisible" :product_id="review_product_id" :website_id="review_website_id" :domain="review_domain" @close="reviewVisible=false" />
  </div>
</template>

<script>
import { Get, Post, Put, Delete, UploadToMultisite } from '@/api/erp/crawl/crawlurl'
import { GetWebs } from '@/api/erp/crawlproduct'
import { Get as GetTargetWebsite } from '@/api/erp/elicink/website'
import { Get as GetProjects } from '@/api/erp/elicink/project'

import qs from 'qs'

import Cookies from 'js-cookie'
import merchant from '@/views/orders/element/merchant'
import prestaproduct from '@/views/prestashop/element/prestaproduct'
import Choosecategory from '@/views/prestashop/element/choosecategory'
import Website_editor from '../erp/elicink/elements/website_editor'
import Platformcompetitiveproduct from './elements/platformcompetitiveproduct'
import Websitereviews from '../prestashop/element/websitereviews'

const souceSiteKey = 'crawl_searchkey_soucekey'

export function getToken(key) {
  const v = Cookies.get(key)
  return v && parseInt(v) || null
}

export function setToken(key, value) {
  return Cookies.set(key, value)
}

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  components: { Websitereviews, Platformcompetitiveproduct, Website_editor, merchant, prestaproduct, Choosecategory },
  data() {
    return {
      review_website_id: '',
      review_product_id: '',
      review_domain: '',
      reviewVisible: false,
      uploaded: 'unuploaded',
      modify_finsihed: '',
      isVisible_platformcompetitiveproduct: false,
      keyword_platformcompetitiveproduct: '',
      price_platformcompetitiveproduct: 0,
      image_platformcompetitiveproduct: '',
      isWebsiteEditorVisible: false,
      operate_domain: '',
      operate_product_id: '',
      item: {},
      operate_local_id: '',
      remoteModifydialogVisible: false,
      currentOpRow: {
        'id': 0,
        'name': '',
        'price': '',
        'description': '',
        'long_description': '',
        'meta_title': '',
        'meta_description': '',
        'meta_keywords': '',
        'web__domain': '',
        'product_id': ''
      },
      uploadVisible: false,
      merchantVisible: false,
      data: [],
      dataWebs: [],
      add_new_website_id: '',
      select_rows: [],
      uploaddata: {
        url: '',
        image: '',
        product_id: '',
        products: [],
        selected_websites: []
      },
      website_options: [],
      remoteSearchWebsite_loading: false,
      direct_upload_dialogVisible: false,
      current_category: {
        target_web_id: '',
        id_of_default_category: '',
        id_of_associated_categories: []
      },
      targetWebs: [],
      select_web: '-1',
      target_web: '',
      listLoading: true,
      innerDialogVisible: false,
      modifyloading: false,
      minRows: 2,
      temp: {
        id: '',
        web_id: 19,
        urls: '',
        ship_from: '',
        tag: ''
      },
      order_by: '',
      order_desc: '',
      // pagination
      kwInput: '',
      project_id: '',
      projectsLoading: false,
      projects: [],
      myself: true,
      tagInput: '',
      pagesize: 10,
      page: 1,
      total: 0
    }
  },

  created() {
    GetProjects()
      .then(response => {
        this.projects = response.data.data
        if (this.project_id === '') {
          this.project_id = this.projects[0].id
          console.log('project_id', this.project_id)
        }
      })
    GetWebs().then((response) => {
      this.dataWebs = response.data
    }).catch(error => {
      console.log(error)
    })
    // GetTargetWebsite().then((response) => {
    //   this.targetWebs = response.data.data;
    // }).catch(error => {
    //   console.log(error)
    // })
    this.select_web = getToken(souceSiteKey) || null
    this.getList()
  },
  methods: {
    handleShowPCP(row) {
      this.keyword_platformcompetitiveproduct = row.name
      this.image_platformcompetitiveproduct = row.image
      this.price_platformcompetitiveproduct = row.price
      this.isVisible_platformcompetitiveproduct = true
    },
    handleShowAddReview(item) {
      this.review_website_id = item.website_id
      this.review_product_id = item.ps_product
      this.review_domain = item.domain
      this.reviewVisible = true
    },
    handleShowEditWebsite(domain) {
      this.operate_domain = domain
      this.isWebsiteEditorVisible = true
    },
    handleRemoveTargetWeb(row) {
      var index = this.uploaddata.selected_websites.filter(function(value, index, arr) {
        if (value.website_id !== row.website_id) {
          return index
        }
      })
      this.uploaddata.selected_websites.splice(index, 1)
    },
    handleAddNewWebsite() {
      let exist = false
      this.uploaddata.selected_websites.forEach(item => {
        if (item.website_id === this.add_new_website_id) {
          exist = true
        }
      })
      if (!exist) {
        this.website_options.forEach(web => {
          if (web.id === this.add_new_website_id) {
            this.uploaddata.selected_websites.push({
              website_id: this.add_new_website_id,
              domain: web.domain,
              id_of_default_category: '',
              id_of_associated_categories: []
            })
          }
        })
      }
    },
    handleSetCategory(row) {
      this.current_category.target_web_id = row.website_id
      this.current_category.id_of_default_category = row.id_of_default_category
      this.current_category.id_of_associated_categories = row.id_of_associated_categories
      this.direct_upload_dialogVisible = true
    },
    remoteSearchWebsite(query) {
      if (query !== '') {
        this.remoteSearchWebsite_loading = true
        GetTargetWebsite(null, qs.stringify({
          kw: query,
          pagesize: 5,
          page: 1
        })).then(response => {
          // this.website_options = this.website_options.concat(response.data.data)
          const id_list = this.website_options.map(item => {
            return item.id
          })
          for (let i = 0; i < response.data.data.length; i++) {
            if (id_list.indexOf(response.data.data[i].id) === -1) {
              this.website_options.push(response.data.data[i])
            }
          }
          this.remoteSearchWebsite_loading = false
        })
      } else {
        this.remoteSearchWebsite_loading = false
      }
    },
    handlePstClose(v) {
      this.remoteModifydialogVisible = false
      this.item.change_price = v.change_price
      console.log(v)
    },
    handleSetDirectUploadCategories(v) {
      this.current_category.id_of_default_category = v.default_catalog
      this.current_category.id_of_associated_categories = v.target_catalogs
      if (this.current_category.id_of_associated_categories.indexOf(2) === -1) {
        this.direct_upload_state = 'warning'
      } else {
        this.direct_upload_state = 'success'
      }
      this.uploaddata.selected_websites.forEach(web => {
        if (web.website_id === this.current_category.target_web_id) {
          web.id_of_default_category = this.current_category.id_of_default_category
          web.id_of_associated_categories = this.current_category.id_of_associated_categories
        }
      })
      console.log(this.uploaddata.selected_websites)
    },
    handleGetRemoteProduct(item) {
      this.operate_domain = item.domain
      this.operate_product_id = item.url
      this.operate_local_id = ''
      this.remoteModifydialogVisible = true
    },
    handleModifyProduct(row) {
      this.item = row
      this.operate_local_id = row.product_id
      this.operate_product_id = ''
      this.operate_domain = ''
      this.remoteModifydialogVisible = true
    },
    filterMethod(query, item) {
      return item.domain.indexOf(query) > -1
    },
    handleSearch() {
      this.page = 1
      // this.temp.web_id = this.select_web
      this.getList()
    },
    handleFixUrl() {
      if (this.temp.urls.length > 0) {
        const clean_urls = []
        const urls = this.temp.urls.split('\n')
        if (urls.length) {
          for (let i = 0; i < urls.length; i++) {
            if (urls[i].indexOf('aliexpress') !== -1) {
              clean_urls.push(urls[i].split('?')[0])
            } else {
              clean_urls.push(urls[i])
            }
          }
        }
        this.temp.urls = clean_urls.join('\n')
      }
    },
    handleAddNew() {
      if (this.temp.id !== '') {
        this.modifyloading = true
        Put(this.temp.id, this.temp).then((response) => {
          this.notify('修改成功')
          this.innerDialogVisible = false
          this.temp.id = ''
          this.temp.urls = ''
          this.modifyloading = false
        })
      } else {
        this.modifyloading = true
        if (this.project_id === '') {
          alert('必须设置项目')
          return
        }
        this.temp.project_id = this.project_id
        Post(this.temp).then((response) => {
          this.temp.id = ''
          this.temp.urls = ''
          this.modifyloading = false
          this.innerDialogVisible = false
          this.getList()
        }).catch(() => {
          this.modifyloading = false
          this.notify('抓取失败')
        })
      }
    },
    handleShowDialog() {
      this.innerDialogVisible = true
    },
    handleUpload() {
      // let message = '确定上传到多个已经选择的网站，是否继续?'
      let invalid_item = false
      this.uploaddata.selected_websites.forEach(item => {
        if (item.id_of_default_category === '') {
          invalid_item = true
        }
      })
      if (invalid_item) {
        this.$message.warning('有网站没有配置默认目录,请注意')
      }
      this.loading = true
      UploadToMultisite(this.uploaddata)
        .then(response => {
          this.$notify({
            title: '已经成功添加到队列',
            message: response.msg,
            type: 'success',
            duration: 2000
          })
          // 移除
          this.loading = false
          this.uploadVisible = false
          this.getList()
          this.uploaddata.products = []
        }).catch(err => {
          this.uploaddata.products = []
          this.$notify({
            title: '失败',
            message: err,
            type: 'success',
            duration: 2000
          })
          this.loading = false
        })
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        web_id: this.select_web,
        project_id: this.project_id,
        kw: this.kwInput,
        modify_finsihed: this.modify_finsihed,
        uploaded: this.uploaded,
        myself: this.myself,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          setToken(souceSiteKey, this.select_web)
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    uploadShown(row) {
      this.uploaddata.url = row.url
      this.uploaddata.product_id = row.product_id
      this.uploaddata.products.push(row.product_id)
      this.uploadVisible = true
      this.uploaddata.image = row.image
      // 可以通用
      // this.uploaddata.selected_websites = []
      // row.uploads.forEach(item => {
      //   this.uploaddata.selected_websites.push({
      //     'website_id': item.website_id,
      //     'id_of_default_category': item.id_of_default_category,
      //     'id_of_associated_categories': item.id_of_associated_categories,
      //     'domain': item.domain
      //   })
      // })
    },
    uploadMultipleSite() {
      for (let i = 0; i < this.select_rows.length; i++) {
        this.uploaddata.products.push(this.select_rows[i].product_id)
      }
      this.uploadVisible = true
    },
    handleSelectionChange(rows) {
      this.select_rows = rows
    },
    handleDelete(row) {
      this.$confirm(`确认要删除  ${row.url}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Delete(row.id).then((response) => {
          this.innerDialogVisible = false
          this.getList()
          this.notify('删除成功')
        })
      }).catch(() => {
      })
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    }
  }
}
</script>

<style scoped>

.app-container >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.app-container >>> .text {
  font-size: 14px;
}

.app-container >>> .pointer {
  cursor: pointer;
  color: #409EFF;
}

.app-container >>> a:visited {
  color: purple;
}

.app-container >>> a:link {
  color: #409EFF;
}

.app-container >>> a:active {
  color: red;
}

.app-container >>> a:hover {
  color: red;
  text-decoration: underline;
}
</style>
